<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
          <el-form ref="dataList2" :inline="true" :model="listQuery" class="demo-form-inline">
            <el-input v-model="listQuery.keyword" class="marginRB10" clearable placeholder="房间名称|房间ID"
                      style="width:200px;"
            ></el-input>
            <el-button class="marginRB10" icon="el-icon-search" type="primary" @click="searchList">搜索</el-button>
          </el-form>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id" style="width:100%;margin-bottom: 20px;"
                  @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="房间名称" prop="room_name"></el-table-column>
          <el-table-column label="房间ID" prop="room_id"></el-table-column>
          <el-table-column label="房主昵称" prop="nickname"></el-table-column>
          <el-table-column label="房主ID" prop="user_code"></el-table-column>
          <el-table-column label="大标记" prop="special_flag_big">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.special_flag_big" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.special_flag_big" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="小标记" prop="special_flag_small">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.special_flag_small" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.special_flag_small" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="大边框" prop="frame_big">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.frame_big" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.frame_big" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="小边框" prop="frame_small">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.frame_small" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.frame_small" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="过期时间" prop="expired_time"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini" type="primary" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="房间ID" prop="room_id">
          <el-input v-model.number="editRulesForm.room_id" placeholder="请输入房间ID"></el-input>
        </el-form-item>
        <el-form-item label="大标记" prop="special_flag_big">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList"

            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传大标记</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="小标记" prop="special_flag_small">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagSmallList"

            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagSmallRemove"
            :on-success="handleSpecialFlagSmallSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传小标记</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="大边框" prop="frame_big">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="frameBigList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleFrameBigRemove"
            :on-success="handleFrameBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传大边框</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="小边框" prop="frame_small">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="frameSmallList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleFrameSmallRemove"
            :on-success="handleFrameSmallSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传小边框</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="过期时间" prop="expired_time">
          <el-date-picker
            v-model="editRulesForm.expired_time"
            placeholder="选择日期时间"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import { deleteData, listData, postAddData, putEditData } from '@/api/room/specialRoomList'

import { IMG_UPLOAD_URL } from '../../data/basic_data'

export default {
  data() {
    return {

      confirmBtn: false,

      specialFlagBigList: [],
      specialFlagSmallList: [],
      frameBigList: [],
      frameSmallList: [],
      // 要修改的当前行的id
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        room_id: [{ required: true, message: '请输入房间ID', trigger: 'blur' }]
      },
      // 受限类型
      limit_typeList: [
        { value: 1, label: '全部' },
        { value: 2, label: 'IP' },
        { value: 3, label: '归属地' }
      ],
      editRulesForm: {
        room_id: undefined,
        special_flag_big: undefined,
        special_flag_small: undefined,
        frame_big: undefined,
        frame_small: undefined,
        expired_time: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        keyword: undefined
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    searchList() {
      this.listQuery.page = 1
      this.getList()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleSpecialFlagBigSuccess() {
      this.editRulesForm.special_flag_big = this.ossLastImgUrl
      this.specialFlagBigList = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove(res) {
      this.specialFlagBigList = []
      this.editRulesForm.special_flag_big = undefined
    },
    handleSpecialFlagSmallSuccess() {
      this.editRulesForm.special_flag_small = this.ossLastImgUrl
      this.specialFlagSmallList = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagSmallRemove(res) {
      this.specialFlagSmallList = []
      this.editRulesForm.special_flag_small = undefined
    },
    handleFrameBigSuccess() {
      this.editRulesForm.frame_big = this.ossLastImgUrl
      this.frameBigList = [{ url: this.ossLastImgUrl }]
    },
    handleFrameBigRemove() {
      this.frameBigList = []
      this.editRulesForm.frame_big = undefined
    },
    handleFrameSmallSuccess() {
      this.editRulesForm.frame_small = this.ossLastImgUrl
      this.frameSmallList = [{ url: this.ossLastImgUrl }]
    },
    handleFrameSmallRemove() {
      this.frameSmallList = []
      this.editRulesForm.frame_small = undefined
    },

    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.keyword) {
        urlData = urlData + `&keyword=${this.listQuery.keyword}`
      }
      listData(urlData).then((response) => {

        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.room_id = row.room_id

      this.editRulesForm.special_flag_big = row.special_flag_big ? row.special_flag_big : ''
      this.specialFlagBigList = row.special_flag_big ? [{ url: row.special_flag_big }] : []

      this.editRulesForm.special_flag_small = row.special_flag_small ? row.special_flag_small : ''
      this.specialFlagSmallList = row.special_flag_small ? [{ url: row.special_flag_small }] : []

      this.editRulesForm.frame_big = row.frame_big ? row.frame_big : ''
      this.frameBigList = row.frame_big ? [{ url: row.frame_big }] : []

      this.editRulesForm.frame_small = row.frame_small ? row.frame_small : ''
      this.frameSmallList = row.frame_small ? [{ url: row.frame_small }] : []

      this.editRulesForm.expired_time = row.expired_time

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.editRulesForm = {
          room_id: undefined,
          special_flag_big: undefined,
          special_flag_small: undefined,
          frame_big: undefined,
          frame_small: undefined,
          expired_time: undefined
        }
        this.specialFlagBigList = []
        this.specialFlagSmallList = []
        this.frameSmallList = []
        this.frameBigList = []
      })

    },
    submitForm(formName) {
      if (this.confirmBtn) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          // alert('submit!');
          if (this.dialogStatus === 'create') {
            let obj = {}
            for (let key in this.editRulesForm) {
              if (this.editRulesForm[key]) {
                obj[key] = this.editRulesForm[key]
              }
            }
            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          } else {
            let obj = {}
            for (let key in this.editRulesForm) {
              if (this.editRulesForm[key]) {
                obj[key] = this.editRulesForm[key]
              }
            }
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      deleteData(this.dataIds).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

/deep/ .el-card__header {
  padding-bottom : 0;
}

/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}
</style>
